package com.test.log4j;

import java.io.File;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.PropertyConfigurator;

@WebServlet("/Log4jInitServlet")
public class Log4jInitServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		
		System.out.println("log4j初始化");
		String log4jLocation = config.getInitParameter("log4j-properties-location");
		
		ServletContext sc = config.getServletContext();
		
		if (log4jLocation == null) {
			System.out.println("没有log4j-properties-location初始化文件，所以使用BasicConfigurator初始化");
			BasicConfigurator.configure();
		}else
		{
			String webAppPath = sc.getRealPath("\\");
			String log4jProp = webAppPath+log4jLocation;
			File file = new File(log4jProp);
			if (file.exists()) {
				System.out.println("使用："+log4jProp+"初始化日志信息");
				PropertyConfigurator.configure(log4jProp);
			}else
			{
				System.out.println("----"+log4jProp+"文件没有找到，使用BasicConfigurator初始化");
				BasicConfigurator.configure();
			}
		}
		super.init(config);
	}
}
